const BaseService = require('./base_service.js');
const CashierLogModel = require('../model/cashier_log_model.js');

class CashierService extends BaseService {

  /**
   * 生成收款二维码
   */
  async generatePaymentQR(input) {
    const db = uniCloud.database();
    const collection = db.collection(CashierLogModel.CL);

    // 生成收银记录
    const cashierData = {
      amount: input.amount,
      paymentMethod: input.paymentMethod,
      storeId: input.storeId,
      storeName: await this.getStoreName(input.storeId),
      operatorId: this.getCurrentAdminId(),
      operatorName: this.getCurrentAdminName(),
      description: input.description || '收银收款',
      status: 0, // 待支付
      createTime: Date.now(),
      updateTime: Date.now()
    };

    const result = await collection.add(cashierData);
    const cashierId = result.id;

    // 生成收款二维码
    const qrCode = await this.generateQRCode(cashierId, input.amount, input.paymentMethod);

    // 更新收银记录
    await collection.doc(cashierId).update({
      qrCode: qrCode,
      updateTime: Date.now()
    });

    return {
      cashierId: cashierId,
      qrCode: qrCode,
      amount: input.amount,
      paymentMethod: input.paymentMethod,
      message: '收款二维码生成成功'
    };
  }

  /**
   * 确认支付
   */
  async confirmPayment(input) {
    const db = uniCloud.database();
    const collection = db.collection(CashierLogModel.CL);

    // 检查收银记录是否存在
    const cashier = await collection.doc(input.cashierId).get();
    if (!cashier.data.length) {
      throw new Error('收银记录不存在');
    }

    const cashierData = cashier.data[0];

    // 检查状态
    if (cashierData.status !== 0) {
      throw new Error('收银记录状态不正确');
    }

    // 更新收银记录
    await collection.doc(input.cashierId).update({
      transactionId: input.transactionId,
      paymentTime: Date.now(),
      status: 1, // 已支付
      updateTime: Date.now()
    });

    return {
      message: '支付确认成功',
      amount: cashierData.amount,
      paymentTime: Date.now()
    };
  }

  /**
   * 获取收银记录
   */
  async getCashierLogs(input) {
    const db = uniCloud.database();
    const collection = db.collection(CashierLogModel.CL);

    // 构建查询条件
    let whereCondition = {};
    
    if (input.storeId) {
      whereCondition.storeId = input.storeId;
    }
    
    if (input.status !== undefined) {
      whereCondition.status = input.status;
    }
    
    if (input.dateRange) {
      const dates = input.dateRange.split(',');
      if (dates.length === 2) {
        whereCondition.createTime = db.command.gte(parseInt(dates[0])).and(db.command.lte(parseInt(dates[1])));
      }
    }

    // 分页查询
    const result = await collection
      .where(whereCondition)
      .orderBy('createTime', 'desc')
      .skip((input.page - 1) * input.size)
      .limit(input.size)
      .get();

    // 获取总数
    const countResult = await collection.where(whereCondition).count();

    return {
      list: result.data,
      total: countResult.total,
      page: input.page,
      size: input.size
    };
  }

  /**
   * 生成收款二维码
   */
  async generateQRCode(cashierId, amount, paymentMethod) {
    // 这里应该调用微信支付或支付宝的二维码生成API
    // 由于需要具体的支付配置，这里先返回模拟的二维码数据
    const qrData = {
      cashierId: cashierId,
      amount: amount,
      paymentMethod: paymentMethod,
      timestamp: Date.now()
    };

    // 模拟生成二维码URL
    const qrCodeUrl = `https://api.example.com/qr/${Buffer.from(JSON.stringify(qrData)).toString('base64')}`;
    
    return qrCodeUrl;
  }

  /**
   * 获取门店名称
   */
  async getStoreName(storeId) {
    const db = uniCloud.database();
    const StoreModel = require('../model/store_model.js');
    const storeCollection = db.collection(StoreModel.CL);
    
    const store = await storeCollection.doc(storeId).get();
    return store.data.length > 0 ? store.data[0].name : '未知门店';
  }

  /**
   * 获取当前管理员ID
   */
  getCurrentAdminId() {
    // 这里应该从请求上下文中获取当前管理员ID
    return 'admin_001';
  }

  /**
   * 获取当前管理员姓名
   */
  getCurrentAdminName() {
    // 这里应该从请求上下文中获取当前管理员姓名
    return '管理员';
  }
}

module.exports = CashierService;
